<template>
  <div class="address-container">
    <!-- 地址列表 -->
    <div v-if="addressList.length > 0" class="address-list">
      <div v-for="(address, index) in addressList" :key="index" class="address-item">
        <div class="address-info">
          <p class="name-phone">
            <span class="name">{{ address.name }}</span>
            <span class="phone">{{ address.tel || address.phone }}</span>
          </p>
          <p class="full-address">
            {{ address.province }}{{ address.city }}{{ address.district || address.county }}{{ address.detail || address.addressDetail }}
          </p>
        </div>
        <div class="address-actions">
          <span class="edit-btn" @click="editAddress(address)">编辑</span>
          <span class="delete-btn" @click="deleteAddress(address)">删除</span>
          <span class="use-btn" @click="useAddress(address)">使用该地址</span>
        </div>
      </div>
    </div>

    <!-- 无地址提示 -->
    <div v-else class="empty-address">
      <img src="/img/暂无商品.svg" alt="无地址" class="empty-image">
      <p class="empty-text">当前没有可用地址</p>
    </div>

    <!-- 底部固定新增按钮 -->
    <div class="add-btn-container">
      <button class="add-btn" @click="addNewAddress">新增地址</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { request, BASE_URL } from '@/Requset/request'

// 地址数据
const addressList = ref([])

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const token = uni.getStorageSync('token')
    const res = await request({
      url: BASE_URL + 'api/getaddress/',
      method: 'GET',
      header: { token }
    })
    console.log('地址列表接口返回：', res.data)
    if (res.data && res.statusCode === 200) {
      if (Array.isArray(res.data)) {
        addressList.value = res.data
      } else if (Array.isArray(res.data.message)) {
        addressList.value = res.data.message
      } else {
        addressList.value = []
      }
    }
  } catch (e) {
    uni.showToast({ title: '获取地址失败', icon: 'none' })
  }
}

// 设为默认地址（前端直接修改本地数据并同步到后端）
const setDefaultAddress = async (address) => {
  uni.showModal({
    title: '设为默认地址',
    content: `确定将此地址设为默认地址吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const token = uni.getStorageSync('token')
          // 统一字段名为 isDefault
          addressList.value.forEach(item => item.isDefault = false)
          address.isDefault = true
          await request({
            url: BASE_URL + 'api/updateaddress/',
            method: 'POST',
            header: { token },
            data: address
          })
          uni.showToast({ title: '设置成功', icon: 'success' })
          setTimeout(() => {
            uni.navigateBack()
          }, 800)
        } catch (e) {
          uni.showToast({ title: '设置失败', icon: 'none' })
        }
      }
    }
  })
}

// 页面每次显示时都刷新地址列表
onShow(() => {
  fetchAddressList()
})

// 新增地址
const addNewAddress = () => {
  uni.navigateTo({
    url: '/pages/add_address/add_address'
  })
}

// 编辑地址
const editAddress = (address) => {
  uni.navigateTo({
    url: `/pages/alter_address/alter_address?id=${address.id}`
  })
}

// 删除地址
const deleteAddress = (address) => {
  uni.showModal({
    title: '提示',
    content: `确定要删除 ${address.name} 的地址吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const token = uni.getStorageSync('token')
          await request({
            url: BASE_URL + 'api/deladdress?address_id=' + encodeURIComponent(address.id),
            method: 'POST',
            header: { token }
          })
          uni.showToast({ title: '删除成功', icon: 'success' })
          // 删除后刷新地址列表
          fetchAddressList()
        } catch (e) {
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

// 使用地址
const useAddress = (address) => {
  console.log('点击使用该地址:', address)
  uni.setStorageSync('selectedAddressId', address.id)
  console.log('已存储 selectedAddressId:', address.id)
  uni.navigateBack()
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

const addressId = ref('')

console.log('addressId类型:', typeof addressId.value, addressId.value)
</script>

<style scoped>
.address-container {
  position: relative;
  min-height: 100vh;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
  background-color: #f5f5f5;
}

.address-list {
  padding: 10px;
}

.address-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.name-phone {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 16px;
}

.name {
  font-weight: bold;
}

.phone {
  color: #666;
}

.full-address {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.address-actions {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px solid #eee;
  text-align: right;
}

.edit-btn, .delete-btn, .use-btn {
  color: #1989fa;
  margin-left: 15px;
  font-size: 14px;
}

.delete-btn {
  color: #f56c6c;
}

.empty-address {
  text-align: center;
  padding-top: 100px;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
}

.empty-text {
  color: #999;
  font-size: 16px;
}

.add-btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.add-btn {
  width: 100%;
  height: 50px;
  background-color: #1989fa;
  color: #fff;
  border: none;
  border-radius: 25px;
  font-size: 16px;
}

.default-btn {
  color: #1989fa;
  margin-right: 10px;
  cursor: pointer;
  font-size: 14px;
}

.default-tag {
  color: #fff;
  background: #1989fa;
  border-radius: 10px;
  padding: 2px 8px;
  margin-right: 10px;
  font-size: 13px;
}
</style>